package com.ea.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * jwt工具类
 */
public class JwtUtils {
	/**加密秘钥**/
	public static final String SECRET = "f9bfb3096ff54b8aae019d55befe2d0c";
	/**header默认头**/
	public static final String HEADER = "token";

	/**
	 * 生成jwt token
	 */
	public static String generateToken(int userId, byte userType, long expire) {
		/*身份类型 0=普通用户 1=技师；2=渠道商；3=代理商；4=管理员*/
		Date nowDate = new Date();
		// 过期时间
		Date expireDate = new Date(nowDate.getTime() + expire * 1000);

		return Jwts.builder().setHeaderParam("typ", "JWT")
				.setSubject(((userType == 0 || userType == 1) ? "APP_" : "CRM_") + userId + "_" + userType)
				.setIssuedAt(nowDate)
				.setExpiration(expireDate)
				.signWith(SignatureAlgorithm.HS256, SECRET)
				.compact();
	}


	/**
	 * 生成jwt token
	 */
	public static String generateToken(String userId, byte userType, long expire) {
		/*身份类型 0=普通用户 1=技师；2=渠道商；3=代理商；4=管理员*/
		Date nowDate = new Date();
		// 过期时间
		Date expireDate = new Date(nowDate.getTime() + expire * 1000);

		return Jwts.builder().setHeaderParam("typ", "JWT")
				.setSubject(((userType == 0 || userType == 1) ? "APP_" : "CRM_") + userId + "_" + userType)
				.setIssuedAt(nowDate)
				.setExpiration(expireDate)
				.signWith(SignatureAlgorithm.HS256, SECRET)
				.compact();
	}

	public static Claims getClaimByToken(String token) {
		try {
			return Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * token是否过期
	 *
	 * @return true：过期
	 */
	public static boolean isTokenExpired(Date expiration) {
		return expiration.before(new Date());
	}
}
